package com.my.easymall.filter;

import com.my.easymall.domain.User;
import com.my.easymall.service.UserService;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;

/**
 * @auther Summerday
 */
@WebFilter("/*")
public class AutoLoginFilter implements Filter {
    private UserService userService = new UserService();
    private User user = new User();
    public void init(FilterConfig config) throws ServletException {
    }
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //session对象如果不存在,或者没有"user",即需要拦截,并进行登陆判断
        if(request.getSession(false)==null||request.getSession().getAttribute("user")==null){
            //没有登录状态
            Cookie[] cs = request.getCookies();
            Cookie autoLogin = null;
            if(cs!=null){
                for(Cookie c:cs){
                    //有自动登录的信息
                    if("autologin".equals(c.getName())){
                        autoLogin = c;
                    }
                }
            }
            //autoLogin找到
            if(autoLogin!=null){
                //获取Cookie中的用户名和密码
                String value = autoLogin.getValue();
                String[] values = value.split("#");
                String username = URLDecoder.decode(values[0],"utf-8");
                String password = values[1];
                //完成自动登录
                //根据数据库查询用户名和密码是否匹配
                user.setUsername(username);
                //md加密算法加密
                user.setPassword(password);
                User loginUser = userService.loginUser(this.user);
                request.getSession().setAttribute("user",loginUser);
            }
        }
        chain.doFilter(request, response);
    }
    public void destroy() {
    }
}
